const express = require('express');
const path = require('path');
const cookieparser = require('cookie-parser');
const multer = require('multer');
const bodyParser = require('body-parser');
const fs = require('fs');
const base = require(path.join(__dirname, './base'));
const loginconf = require(path.join(__dirname, './../conf/login.conf'));
const projectconf = require(path.join(__dirname, './../conf/project.conf'));
const loginpage = path.join(__dirname, './../'+loginconf.loginhtml);
const userjson = path.join(__dirname, './../'+loginconf.userjson);
let router = express.Router(); 

router.get('/login', bodyParser.json(), function (req, res) {
    /**准备参数 */
    let callback = projectconf.getIpPort() + "/" + loginconf.loginparm.callback;
    let tokenname = loginconf.loginparm.tokenname;
    let usecookie = loginconf.loginparm.usecookie;

    /**拼接参数 */
    let param = "?callback="+ callback
                + "&tokenname="+ tokenname
                + "&usecookie="+ usecookie

    /**拼接url */
    let url = loginconf.loginurl + param;

    res.redirect(url)
});

router.get('/login_pt', bodyParser.json(), function (req, res) {
    res.sendFile(loginpage);
});

router.get('/login_pt/judge', async function (req, res) {
    let param = req.query;
    /**校验登录 */
    let username = param.username;
    let password = param.password;
    let role = '';
    
    /**json加载用户信息 */
    let json = await fs.readFileSync(userjson, 'utf-8')
    let dbuser =  JSON.parse(json.toString());
    
    if(username==dbuser.user_admin.name && password==dbuser.user_admin.pwd){
        role = dbuser.user_admin.role;
    }else if(username==dbuser.user_opt.name && dbuser.user_opt.pwd){
        role = dbuser.user_opt.role;
    }else{
        res.send('msg:用户名或密码错误');
    }

    if(role){
        /**拼接参数 */
        param = "?username="+ username
                    + "&password="+ password
                    + "&role="+ role;
        
        let url = projectconf.getIpPort() + "/" + loginconf.loginparm.callback + param;
        res.send(url);
    }
});

router.get('/logout', async function (req, res) {
    console.log('退出登录逻辑代码');
    base.send(res,'退出登录未开发');
});

//导出该路由
module.exports = router;